package org.rapan;

import java.util.Set;

import javax.naming.InitialContext;
import javax.naming.NamingException;

import org.rapan.EJB.ConsultantInt;
import org.rapan.jpa.Consultant;

import com.vaadin.event.FieldEvents.TextChangeEvent;
import com.vaadin.event.FieldEvents.TextChangeListener;
import com.vaadin.ui.Button;
import com.vaadin.ui.Button.ClickListener;
import com.vaadin.ui.Label;
import com.vaadin.ui.TextField;
import com.vaadin.ui.VerticalLayout;
import com.vaadin.ui.Button.ClickEvent;
import com.vaadin.ui.themes.BaseTheme;

@SuppressWarnings("serial")
public abstract class SearchLayout extends VerticalLayout {

	private VerticalLayout searchLayout = new VerticalLayout();
	private TextField searchField = new TextField("Search");

	public SearchLayout() {
		setSpacing(true);
		setMargin(true);

		addComponent(searchField);
		addComponent(searchLayout);

		searchField.setImmediate(true);
		searchField.addListener(new TextChangeListener() {

			public void textChange(TextChangeEvent event) {
				searchAndShowConsultants(event.getText());
			}
		});

	}

	protected void searchAndShowConsultants(String text) {
		searchLayout.removeAllComponents();
		if (!"".equals(text))
			try {
				InitialContext context = new InitialContext();
				ConsultantInt conInt = (ConsultantInt) context
						.lookup("Consult/ConsultantBean/local");
				Set<Consultant> conSet = conInt.findConsultants(text);
				if (!conSet.isEmpty())
					for (final Consultant c : conSet) {
						Button conButton = new Button(c.getFullName());
						conButton.addListener(new ClickListener() {

							public void buttonClick(ClickEvent event) {
								consultantSelected(c);
							}
						});
						conButton.addStyleName(BaseTheme.BUTTON_LINK);
						searchLayout.addComponent(conButton);
					}
				else
					searchLayout
							.addComponent(new Label(
									"No consultant with Email or name containing the given match is found."));

			} catch (NamingException e) {
				e.printStackTrace();
			}

	}

	public abstract void consultantSelected(Consultant c);

}
